package com.app.twth.ui.adjust.retallytask.submit;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.base.BaseCameraPhotoActivity;
import com.app.twth.bean.FilePathListDTO;
import com.app.twth.bean.PhotoBean;
import com.app.twth.databinding.ActivityRetallySubmitBinding;
import com.app.twth.ui.adjust.retally.ReTally;
import com.app.twth.ui.adjust.retally.ReTallyQr;
import com.app.twth.ui.adjust.retally.ReTallyViewModel;
import com.app.twth.ui.checkin.PhotoAdapter;
import com.app.twth.ui.tally.sku.SkuInfo;
import com.app.twth.ui.tally.sku.SkuInfoQr;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @describe :
 */
public class ReTallyTaskSubmitctivity extends BaseCameraPhotoActivity<ActivityRetallySubmitBinding, ReTallyViewModel> {
    private String TAG = getClass().getSimpleName();
    private int type = 0;
    private int position = 0;
    private List<PhotoBean> photo1Paths = new ArrayList<>();
    private PhotoAdapter photo1Adapter;
    private SkuInfo skuInfo;

    @Override
    protected void initListener() {
        viewModel.fileUploadMutableLiveData.observe(this, data -> {
            Log.e(TAG, "type():" + data.getType() + ",position:" + data.getPosition());
            if (photo1Paths.size() > data.getPosition()) {
                PhotoBean photoBean = photo1Paths.get(data.getPosition());
                photoBean.setUrlImg(data.getPath());
            }

            if (data.isSubmit()) {
                submitData();
            }
        });
        viewModel.tallySkuInfoLiveData.observe(this, data -> {
            skuInfo = data;
            setSkuData(true, skuInfo, skuInfo.isSubmit());
        });
        viewModel.submitLiveData.observe(this, code -> {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "ReTally(Submit)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext(getString(R.string.submit));
        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        viewModel.reTallyLiveData.setValue((ReTally) bundle.getSerializable("data"));

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.tvCartons.requestFocus();
        binding.tvCartons.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvPcs.setOnFocusChangeListener(onFocusChangeListener);

        photo1Paths.add(new PhotoBean());
        photo1Adapter = new PhotoAdapter(this, photo1Paths, 0, position -> {
            this.position = position;
            requestCamera("photo1");
        }, str -> {
        });
        GridLayoutManager photo1Manager = new GridLayoutManager(this, 3);
        binding.rvPhoto1.setLayoutManager(photo1Manager);
        binding.rvPhoto1.setAdapter(photo1Adapter);

        if (!Utils.isEmpty(viewModel.reTallyLiveData.getValue().getSku())) {
            barcodeStr = viewModel.reTallyLiveData.getValue().getSku();
            Log.e(TAG, "barcodeStr:" + barcodeStr);
            viewModel.code.setValue(barcodeStr);
            SkuInfoQr skuInfoQr = new SkuInfoQr();
            skuInfoQr.setBarcode(barcodeStr);
            skuInfoQr.setTyp(1);
            skuInfoQr.setOrderId(viewModel.reTallyLiveData.getValue().getOrderId());
//            skuInfoQr.setTaskId(viewModel.reTallyLiveData.getValue().getTaskId());
            viewModel.getTallySkuInfo(skuInfoQr, false);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                setScan();
                break;
            case R.id.tv_reset:
                bottomLayoutBinding.tvHint.setText("");
                binding.tvCartons.setText("");
                binding.tvPcs.setText("");
                break;
            case R.id.iv_cartons:
                String cartonsQty = binding.tvCartons.getText().toString();
                if (Utils.isEmpty(cartonsQty)) {
                } else if (Integer.parseInt(cartonsQty) > 1) {
                    binding.tvCartons.setText((Integer.parseInt(cartonsQty) - 1) + "");
                } else {
                    binding.tvCartons.setText("0");
                }
                break;
            case R.id.iv_pcs:
                String pcsQty = binding.tvPcs.getText().toString();
                if (Utils.isEmpty(pcsQty)) {
                } else if (Integer.parseInt(pcsQty) > 1) {
                    binding.tvPcs.setText((Integer.parseInt(pcsQty) - 1) + "");
                } else {
                    binding.tvPcs.setText("0");
                }
                break;
            case R.id.tv_next:
                submitData();
                break;
        }
    }

    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                type = 0;
                return;
            }

            switch (v.getId()) {
                case R.id.tv_cartons:
                    type = 0;
                    break;
                case R.id.tv_pcs:
                    type = 1;
                    break;
            }
        }
    };

    @Override
    public void getScanninCode() {
        bottomLayoutBinding.tvHint.setText("");
        judgeSku();
    }

    private void judgeSku() {
        new AsyncTask<String, Integer, Integer>() {

            @Override
            protected Integer doInBackground(String... strings) {
                if (barcodeStr.equalsIgnoreCase(viewModel.reTallyLiveData.getValue().getSku())) {
                    return type;
                }
                if (skuInfo != null) {
                    if (barcodeStr.equalsIgnoreCase(skuInfo.getSku())) {
                        return type;
                    }
                    List<String> barcodes = skuInfo.getBarcodeList();
                    if (barcodes != null) {
                        for (String barcode : barcodes) {
                            if (barcodeStr.equalsIgnoreCase(barcode)) {//扫描的是barcode
                                return type;
                            }
                        }
                    }
                }
                return 5;

            }

            @Override
            protected void onPostExecute(Integer i) {
                super.onPostExecute(i);
                switch (i) {
                    case 0:
                        String ctn = binding.tvCartons.getText().toString();
                        if (Utils.isEmpty(ctn)) {
                            binding.tvCartons.setText(1 + "");
                        } else {
                            binding.tvCartons.setText((1 + Integer.parseInt(ctn)) + "");
                        }
                        break;
                    case 1:
                        String pcs = binding.tvPcs.getText().toString();
                        if (Utils.isEmpty(pcs)) {
                            binding.tvPcs.setText(1 + "");
                        } else {
                            binding.tvPcs.setText((1 + Integer.parseInt(pcs)) + "");
                        }
                        break;
                    case 5:
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        break;
                }

            }
        }.execute();
    }

    private void reset() {
        binding.tvCartons.setText("");
        binding.tvPcs.setText("");
        binding.layoutPcs.setVisibility(View.GONE);
        photo1Paths.clear();
        photo1Paths.add(new PhotoBean());
        photo1Adapter.setData(photo1Paths);
    }

    private void setSkuData(boolean isOk, SkuInfo skuUpType, boolean isSubmit) {
        Log.e(TAG, "setSkuData");
        if (skuUpType == null) {
            return;
        }

        setPutType(skuUpType);

        if (isOk && isSubmit) {
            submitData();
        }
    }

    private void setPutType(SkuInfo skuUpType) {
        if (skuUpType.getPutawayType() == 1) {
            binding.layoutPcs.setVisibility(View.GONE);
            binding.tvCartons.setEnabled(true);
            binding.tvCartons.setText("1");
            binding.tvCartons.requestFocus();
        } else {
            binding.layoutPcs.setVisibility(View.VISIBLE);
            binding.tvPcs.setEnabled(true);
            binding.tvCartons.setText("1");
            binding.tvPcs.setText("1");
            binding.tvCartons.requestFocus();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void getImgPath(String path) {
        setPath(path);
    }

    private void setPath(String pathImage) {
        Log.e(TAG, "setPath,pathImage:" + pathImage);
        if (!pathImage.contains("http")) {//选择的图片
            String fileName = "lpnphoto";
            viewModel.fileUpload(viewModel.reTallyLiveData.getValue().getIbLpn(), fileName, pathImage, position, false, false);
        }
        PhotoBean imgUrl = new PhotoBean();
        imgUrl.setPathImg(pathImage);
        imgUrl.setUrlImg(pathImage);
        photo1Paths.add(position, imgUrl);

        if (!Utils.isEmpty(photo1Paths.get(photo1Paths.size() - 1).getPathImg())) {
            photo1Paths.add(new PhotoBean());
        }

        if (photo1Adapter != null) {
            photo1Adapter.setData(photo1Paths);
        }
    }

    private void submitData() {
        Log.e(TAG, "setSubmit");
        ReTallyQr tallyQr = new ReTallyQr();
        String cartons = binding.tvCartons.getText().toString();
        String pcs = binding.tvPcs.getText().toString();
        if (skuInfo == null || skuInfo.getPutawayType() == 0) {
            if (Utils.isEmpty(cartons) && Utils.isEmpty(pcs)) {
                ToastUtil.showToast("please input cartons");
                return;
            }
            if (Integer.parseInt(cartons) < 1) {
                ToastUtil.showToast("please input cartons");
                return;
            }
            tallyQr.setCtnQty(Integer.parseInt(cartons));
            tallyQr.setPcsQty(0);
            tallyQr.setQty(Integer.parseInt(cartons));
        } else if (skuInfo.getPutawayType() == 1) {
            if (Utils.isEmpty(cartons) && Utils.isEmpty(pcs)) {
                ToastUtil.showToast("please input cartons");
                return;
            }
            if (Integer.parseInt(cartons) < 1) {
                ToastUtil.showToast("please input cartons");
                return;
            }

            tallyQr.setCtnQty(Integer.parseInt(cartons));
            tallyQr.setPcsQty(0);
            tallyQr.setQty(Integer.parseInt(cartons));
        } else {
            if (Utils.isEmpty(cartons) && Utils.isEmpty(pcs)) {
                ToastUtil.showToast("please input cartons");
                return;
            }
            if (Integer.parseInt(cartons) < 1) {
                ToastUtil.showToast("please input cartons");
                return;
            }

            if (Utils.isEmpty(pcs)) {
                ToastUtil.showToast("please input pcs");
                return;
            }
            if (Integer.parseInt(pcs) < 1) {
                ToastUtil.showToast("please input pcs");
                return;
            }
            if (Integer.parseInt(cartons) > Integer.parseInt(pcs)) {
                ToastUtil.showToast("PCS need be equal or greater than CTN");
                return;
            }

            tallyQr.setCtnQty(Integer.parseInt(cartons));
            tallyQr.setPcsQty(Integer.parseInt(pcs));
            tallyQr.setQty(Integer.parseInt(pcs));
        }

        if (System.currentTimeMillis() - timeMillis < 2000) {
            return;
        }
        timeMillis = System.currentTimeMillis();

        List<String> lpnPathList = new ArrayList<>();
        if (photo1Paths.size() > 0) {
            for (int i = 0; i < photo1Paths.size(); i++) {
                PhotoBean photoBean = photo1Paths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(viewModel.reTallyLiveData.getValue().getIbLpn(), "photo1", s, position, true, true);
                        return;
                    }
                    lpnPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(viewModel.reTallyLiveData.getValue().getIbLpn(), "photo1", photoBean.getPathImg(), position, true, true);
                    return;
                }
            }
        }
        if (lpnPathList.size() == 0) {
            ToastUtil.showToast("Please add lpn photos");
            return;
        }

//        tallyQr.setTaskId(viewModel.reTallyLiveData.getValue().getOrderId());
        if (viewModel.reTallyLiveData.getValue().getTaskId() != 0) {
            tallyQr.setTaskId(viewModel.reTallyLiveData.getValue().getTaskId());
        }
        tallyQr.setOrderId(viewModel.reTallyLiveData.getValue().getOrderId());
        tallyQr.setIbLpn(viewModel.reTallyLiveData.getValue().getIbLpn());
        tallyQr.setBarcode(viewModel.reTallyLiveData.getValue().getSku());

        List<FilePathListDTO> filePathList = new ArrayList<>();

        FilePathListDTO lpnFilePathListDTO = new FilePathListDTO();
        lpnFilePathListDTO.setName("lpnPhoto");
        lpnFilePathListDTO.setPathList(lpnPathList);
        filePathList.add(lpnFilePathListDTO);
        tallyQr.setFilePathList(filePathList);

        viewModel.tallyReTallySubmit(tallyQr);
    }
}
